package com.example.photo_sharing.page.navigation;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.NetworkOnMainThreadException;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.page.adapter.listItemAdapter;
import com.example.photo_sharing.page.others.Detailed;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.example.photo_sharing.entity.FindList;
import com.example.photo_sharing.entity.FindListItem;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;



public class Find extends Fragment {

    private App app;
    private FindList fl = new FindList();

    private RecyclerView recyclerView; //定义ReclerView控件
    private View root;//定义view来设置fragment中的layout
    private ArrayList<FindListItem> goodsEntities = new ArrayList<>();
    private ArrayList<FindListItem> goodsEntities_upload = new ArrayList<>();
    private listItemAdapter myadpater;

    private String userId;
    private boolean sign_of_empty = true;
    private boolean sign_of_login = true;

    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp;

    public Find() {
        // Required empty public constructor
    }

    private int pages;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (App)getActivity().getApplication();
        sharedPreferences = getActivity().getSharedPreferences("userInfo",getActivity().MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);
        sign_of_login = usp.isLogin();
        System.out.println(sign_of_login);
        if(sign_of_login){
            userId = usp.getUserId();
            System.out.println(userId);
        }

        get(app.getCurrent());


    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){

        root = inflater.inflate(R.layout.navigation_find,container,false);

//        swipeRefreshLayout = (SwipeRefreshLayout)root.findViewById(R.id.find_refresh);
//        handleDownPullUpdate();
//
//        handleUpLoadMore();


        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        app.setDelay(300);

        initRecyclerView(goodsEntities_upload);

        pages = app.getCurrent();

        SmartRefreshLayout refreshLayout = getActivity().findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                get(app.getCurrent());
                app.setDelay(300);
                initRecyclerView(goodsEntities_upload);
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                System.out.println("asaaaaaaaaaaaa");
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                get(++pages);
                app.setDelay(300);
                goodsEntities.addAll(goodsEntities_upload);
                myadpater.notifyDataSetChanged();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
    }

    //获取发现列表的内容
    private void get(int current){

        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/photo/share?"
                    +"current="+current
                    +"&size="+app.getSize()
                    +"&userId="+userId;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            e.printStackTrace();
            System.out.println("失败");
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String responseData = response.body().string();

            System.out.println("返回的json字符串"+responseData);

            JSONObject jsonObject  = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);

            if(jsonObject == null){
                return;
            }
            else{
                sign_of_empty = false;
            }

            JSONArray jsonArray = jsonObject.getJSONArray("records");

            fl.setCurrent(jsonObject.getInteger("total"));
            fl.setSize(jsonObject.getInteger("size"));
            fl.setTotal(jsonObject.getInteger("current"));

            //将获取的图片链接存入数据中
            ArrayList<FindListItem> fli = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                FindListItem jo = JSON.toJavaObject(object,FindListItem.class);
                JSONArray ja = object.getJSONArray("imageUrlList");
                List<String> img_url = ja.toJavaList(String.class);
                jo.setImageUrlList(img_url);
                fli.add(i,jo);
            }
            fl.setRecords(fli);
            goodsEntities_upload = fli;
            System.out.println(goodsEntities.size());
            System.out.println("成功");
        }
    };

    private void initRecyclerView(ArrayList<FindListItem> goodsEntities_show) {
        recyclerView = (RecyclerView)root.findViewById(R.id.find_recyclerview);
        myadpater = new listItemAdapter(getActivity(),goodsEntities_show);
        recyclerView.setAdapter(myadpater);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));

        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        myadpater.setOnItemClickListener(new listItemAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, FindListItem data) {
                if(usp.isLogin()){
                    Intent intent = new Intent(getActivity(), Detailed.class);
                    intent.putExtra("shareId",data.getId());
                    intent.putStringArrayListExtra("urls",(ArrayList<String>) data.getImageUrlList());
                    intent.putExtra("data",data);
                    startActivity(intent);
                }
                else{
                    Toast.makeText(getActivity(),"请先登录",Toast.LENGTH_LONG).show();
                }
            }
        });
    }



//    private void handleDownPullUpdate() {
//        swipeRefreshLayout.setEnabled(true);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                get();
//                initRecyclerView();
//
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //System.out.println("running");
//                        swipeRefreshLayout.setRefreshing(false);
//                    }
//                },1000);
//            }
//        });
//        //System.out.println("success");
//    }
//
//    /**
//     * 添加十条数据
//     * */
//    private void addRecyclerData(){
//
//    }
//
//    private void handleUpLoadMore() {
//        //加载显示，避免重复加载
//        boolean load = true;
//
//        LinearLayoutManager layoutManager;
//        layoutManager = new LinearLayoutManager(this.getContext());
//
//        recyclerView = (RecyclerView)root.findViewById(R.id.find_recyclerview);
//        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            /**
//             * 当 RecyclerView 的滚动状态改变时调用的回调方法。
//             * 参数：
//             * recyclerView – 滚动状态已更改的 RecyclerView。
//             * newState – 更新的滚动状态。 SCROLL_STATE_IDLE 、 SCROLL_STATE_DRAGGING或SCROLL_STATE_SETTLING 。
//             * */
//            @Override
//            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//            }
//
//            /**
//             * 当 RecyclerView 滚动时调用的回调方法。 这将在滚动完成后调用。
//             * 如果在布局计算后可见项目范围发生变化，也会调用此回调。 在这种情况下，dx 和 dy 将为 0。
//             * */
//            @Override
//            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                //当dy为负时是往上   正才是往下
//                if (dy > 0) {
//                    int visibleItemCount = layoutManager.getChildCount();    //得到显示屏幕内的list数量
//                    int totalItemCount = layoutManager.getItemCount();    //得到list的总数量
//                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();//得到显示屏内的第一个list的位置数position
//                    System.out.println(visibleItemCount+" "+totalItemCount+" "+firstVisiblePosition+"   "+dy+"   "+dx);
//                    if (load && (visibleItemCount + firstVisiblePosition) >= totalItemCount) {
//                        //添加数据，或者用网络请求
//                        //记住加载完成后需要 load = false 无论成功与否
//                        addRecyclerData();
//                    }
//                }
//            }
//        });
//    }
}
